package com.test.service.impl;

import com.test.dao.ArticleMapper;
import com.test.pojo.Article;
import com.test.pojo.SystemUser;
import com.test.service.ArticleService;
import com.test.util.helper.MyPage;
import com.test.vo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

//    @Override
//    public List<Article> getAll(Byte newsState,String newsTitle, Integer pageNum, Integer pageSize){
//        return articleMapper.getAll(newsState, newsTitle, Integer pageNum, Integer pageSize);
//    }

    @Override
    public MyPage<Article> getAll(Byte newsState, String newsTitle, Integer pageNum, Integer pageSize) {
        List<Article> list = articleMapper.getAll(newsState, newsTitle, pageNum, pageSize);
        Long count = articleMapper.countAllByLike(Integer.valueOf(newsState), newsTitle);
        MyPage<Article> page = new MyPage<>(pageNum, pageSize, count , 5, list);
        return page;
    }

    @Override
    public Article selectOneByTitle(String title) {
        return articleMapper.selectOneByTitle(title);
    }

    @Override
    public boolean deleteByPrimaryKey(String newsId) {
        return articleMapper.deleteByPrimaryKey(newsId);
    }

    @Override
    public boolean insert(Article article) {
        return articleMapper.insert(article);
    }

    @Override
    public ResponseMessage add(Article article, MultipartFile multipartFile,
                               HttpServletRequest request) throws ParseException {
        ResponseMessage responseMessage = sharedResponseMessage(article, multipartFile, request, true);
        if(responseMessage.getMessage() == null){
            article.setNewsId(UUID.randomUUID().toString());
            boolean flag = articleMapper.insertSelective(article);
            if(flag){
                responseMessage.setSuccess(true).setCode(200).setMessage("添加成功");
            }else {
                responseMessage.setSuccess(false).setCode(150).setMessage("添加失败");
            }
        }

        return responseMessage;
    }

    @Override
    public boolean deleteSelected(String[] items) {
        return articleMapper.deleteSelected(items);
    }

    @Override
    public ResponseMessage update(Article article, MultipartFile multipartFile, HttpServletRequest request) throws ParseException {
        ResponseMessage responseMessage = sharedResponseMessage(article, multipartFile, request, false);
        if(responseMessage.getMessage() == null){
            boolean flag = articleMapper.updateByPrimaryKeySelective(article);
            if(flag){
                responseMessage.setSuccess(true).setCode(200).setMessage("修改成功");
            }else {
                responseMessage.setSuccess(false).setCode(150).setMessage("修改失败");
            }
        }

        return responseMessage;
    }

    @Override
    public Article selectOneByNewsId(String newsId) {
        return articleMapper.selectOneByNewsId(newsId);
    }

    //添加 修改
    public ResponseMessage sharedResponseMessage(Article article, MultipartFile multipartFile,
                               HttpServletRequest request, boolean addOrUpdate){
        ResponseMessage responseMessage = new ResponseMessage();
        if(!multipartFile.isEmpty()){
            String originalFilename = multipartFile.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.indexOf("."));
            String fileCurName = UUID.randomUUID().toString()+substring;
            if(multipartFile.getSize() <= 5242880){
                List<String> strings = Arrays.asList(".jpg", ".jpeg", ".gif", ".png");
                if(strings.contains(substring)){
                    String realPath = request.getServletContext().getRealPath("/update/");
                    String path = UUID.randomUUID().toString();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String formatDate = dateFormat.format(new Date());
                    StringBuilder builder = new StringBuilder(formatDate);
                    builder.append("/");
                    String[] strLists = path.split("-");
                    for(int i=0; i<strLists.length-1; i++){
                        builder.append(strLists[i]).append("/");
                    }
                    realPath += File.separator + builder.toString();
                    File file = new File(realPath);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    File file1 = new File(file, fileCurName);
                    try {
                        multipartFile.transferTo(file1);
                        article.setNewsImgUrl("/upload/"+builder.toString()+"/"+fileCurName);
                        SystemUser user = (SystemUser)request.getSession().getAttribute("user");
                        article.setUserId(user.getUserId());
                        article.setNewsPublishTime(dateFormat.parse(formatDate));
                    } catch (IOException | ParseException e) {
                        e.printStackTrace();
                        responseMessage.setSuccess(false).setCode(113).setMessage("文件上传失败");
                    }
                }else {
                    responseMessage.setSuccess(false).setCode(112).setMessage("文件格式不正确");
                }
            }else {
                responseMessage.setSuccess(false).setCode(114).setMessage("文件大小超过5M");
            }
        }else {
            if(addOrUpdate == true){
                if(multipartFile.getSize() == 0){
                responseMessage.setSuccess(false).setCode(111).setMessage("文件内容不能为空");
                }
            }

        }

        return responseMessage;

    }
}
